import lombok.SneakyThrows;

import java.net.ServerSocket;
import java.net.Socket;


public class Server extends  Port implements  Runnable{
    Socket currClient;
    String inetAddress;

    Server(Socket currClient,String inetAddress){
        this.currClient = currClient;
        this.inetAddress  = inetAddress;
    }

    public static void main(String[] args) {
        try {
            //初始化ServerSocket
            ServerSocket server = new ServerSocket(2000);
            System.out.println("Waiting for client connection...");

            while(true) {
                //阻塞等待客户端连接，初始化Socket
                Socket client = server.accept();
                String inetAddress = client.getInetAddress().toString().substring(1);
                System.out.println(client.getInetAddress().getHostName() + "/" + client.getInetAddress().getHostAddress() + " connection succeeded.");
                // 启动一个Server线程为客户端服务
                new Thread(new Server(client,inetAddress)).start();
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }

    @SneakyThrows
    public void run() {
        try {
            // 发送信息线程
            new SendThread(currClient).start();
            // 接收信息线程
            new ReplyThread(currClient,inetAddress).start();
        } catch (Exception e) {
            System.out.println("异常关闭");
        } finally {
            // SendThread和ReplyThread之一的线程释放了锁，才能关闭Socket
            synchronized (lock) {
                lock.wait();
            }
            currClient.close();
        }
    }
}